package com.woniuxy.handler;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.woniuxy.config.AlipayConfig;
import com.woniuxy.mapper.BalanceHistoryMapper;
import com.work.framework.pojo.Balance;
import com.work.framework.pojo.BalanceHistory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;


/**
 * 支付宝接口
 */
@Controller
@RequestMapping("/alipay")
@Api(value = "支付宝接口", tags = "用户")
public class PayHandler {

    @Autowired
    BalanceHistoryMapper balanceHistoryMapper;

    @ApiOperation(value = "支付（充值）", notes = "传入订单号，金额完成支付")
    @GetMapping("/pay/{total_amount}")
    public void pay(HttpServletRequest request, HttpServletResponse response,@PathVariable("total_amount")Double total_amount) throws Exception {
        // 获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type);
        // 设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        //将金额存入session
        HttpSession session = request.getSession();
        session.setAttribute("total_amount", total_amount);

        //生成订单号
        String out_trade_no = System.currentTimeMillis() + "";
        String subject = "码上拍订单";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        // 请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        response.setContentType("text/html;charset=utf8");
        // 输出
        response.getWriter().println(result);
    }

    @ApiOperation(value = "异步调用", notes = "用于支付成功后进行数据库操作")
    @RequestMapping("/notify")
    public void updateOrder(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        if (signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            if (trade_status.equals("TRADE_SUCCESS")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //插入订单号，支付宝交易号，交易状态,存入数据库
                System.out.println("交易成功");
                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
                Date date = new Date();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String bhTime = simpleDateFormat.format(date);
                BalanceHistory balanceHistory = new BalanceHistory();
                balanceHistory.setBhState(1);
                balanceHistory.setBhTime(bhTime);
                //有点问题  晚点改
                HttpSession session = request.getSession();
                Double money = (Double) session.getAttribute("total_amount");
                balanceHistory.setMoney(money);
                balanceHistory.setUid(1);
                balanceHistoryMapper.add(balanceHistory);
                Balance balance = balanceHistoryMapper.findBalance(1);
                BigDecimal amount = balance.getAmount();
                amount = amount.add(new BigDecimal(money));
                balanceHistoryMapper.updateMoney(1, amount);
            }
            response.getWriter().println("success");

        } else {//验证失败
            System.out.println("交易失败");
            response.getWriter().println("fail");
        }

    }

    @ApiOperation(value = "同步调用", notes = "用于支付成功后跳转页面")
    @RequestMapping("/syn")
    public void syn(HttpServletResponse response) {
        try {
            response.sendRedirect("https://www.baidu.com/");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "退款", notes = "传入交易单号，支付交易号，金额,完成退款")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "out_trade_no", value = "商家订单号"),
            @ApiImplicitParam(name = "trade_no", value = "支付宝交易号"),
            @ApiImplicitParam(name = "refund_amount", value = "退款金额")
    })
    @RequestMapping("/refund/{out_trade_no}/{trade_no}/{refund_amount}")
    public void refund(HttpServletRequest request, HttpServletResponse response, @PathVariable("out_trade_no") String out_trade_no, @PathVariable("trade_no") String trade_no, @PathVariable("refund_amount") Double refund_amount) throws Exception {
        System.out.println("退款测试。。。");
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        String refund_reason = "就是要退款";


        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"trade_no\":\"" + trade_no + "\","
                + "\"refund_amount\":\"" + refund_amount + "\","
                + "\"refund_reason\":\"" + refund_reason
                + "\"}");

        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
        response.setContentType("text/html;charset=utf8");
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONObject jsonObject1 = jsonObject.getJSONObject("alipay_trade_refund_response");
        String str = jsonObject1.getString("code");
        System.out.println("状态码：" + str);

        System.out.println("退款成功");
        response.sendRedirect("https://www.baidu.com/");
    }

}
